/**
 * Created by 1257D on 2016-03-23.
 */
define(
    ["app/core/base",
        "app/core/util",
        "../echartsMeta",
        "jquery",
        "underscore",
        'JSONParse',
        'loglevel',
        "echarts"
    ],
    function (Chart, Util, Meta, $, _, JSON, log, ec) {

        var mapType = "china";

        function randomData() {
            return Math.round(Math.random() * 1000);
        }

        function FindMapJsFile(mapType) {
            var jsFile = 'libs/echarts/map/js/china';
            // '北京', '天津', '上海', '重庆',
            // 23个省
            /* '广东', '青海', '四川', '海南', '陕西',
             '甘肃', '云南', '湖南', '湖北', '黑龙江',
             '贵州', '山东', '江西', '河南', '河北',
             '山西', '安徽', '福建', '浙江', '江苏',
             '吉林', '辽宁', '台湾',*/
            // 5个自治区
            /* '新疆', '广西', '宁夏', '内蒙古', '西藏',*/
            // 2个特别行政区
            /* '香港', '澳门'*/
            switch (mapType) {
                case "china":
                    jsFile = 'libs/echarts/map/js/china';
                    break;
                case "world":
                    jsFile = 'libs/echarts/map/js/world';
                    break;
                case "北京":
                    jsFile = 'libs/echarts/map/js/province/beijing';
                    break;
                case "天津":
                    jsFile = 'libs/echarts/map/js/province/tianjin';
                    break;
                case "上海":
                    jsFile = 'libs/echarts/map/js/province/shanghai';
                    break;
                case "重庆":
                    jsFile = 'libs/echarts/map/js/province/chongqing';
                    break;
                case "广东":
                    jsFile = 'libs/echarts/map/js/province/guangdong';
                    break;
                case "青海":
                    jsFile = 'libs/echarts/map/js/province/qinghai';
                    break;
                case "四川":
                    jsFile = 'libs/echarts/map/js/province/sichuan';
                    break;
                case "海南":
                    jsFile = 'libs/echarts/map/js/province/hainan';
                    break;
                case "陕西":
                    jsFile = 'libs/echarts/map/js/province/shanxi1';
                    break;
                case "甘肃":
                    jsFile = 'libs/echarts/map/js/province/gansu';
                    break;
                case "云南":
                    jsFile = 'libs/echarts/map/js/province/yunnan';
                    break;
                case "湖南":
                    jsFile = 'libs/echarts/map/js/province/hunan';
                    break;
                case "湖北":
                    jsFile = 'libs/echarts/map/js/province/hubei';
                    break;
                case "黑龙江":
                    jsFile = 'libs/echarts/map/js/province/heilongjiang';
                    break;
                case "贵州":
                    jsFile = 'libs/echarts/map/js/province/guizhou';
                    break;
                case "山东":
                    jsFile = 'libs/echarts/map/js/province/shandong';
                    break;
                case "江西":
                    jsFile = 'libs/echarts/map/js/province/jiangxi';
                    break;
                case "河南":
                    jsFile = 'libs/echarts/map/js/province/henan';
                    break;
                case "河北":
                    jsFile = 'libs/echarts/map/js/province/hebei';
                    break;
                case "山西":
                    jsFile = 'libs/echarts/map/js/province/shanxi';
                    break;
                case "安徽":
                    jsFile = 'libs/echarts/map/js/province/anhui';
                    break;
                case "福建":
                    jsFile = 'libs/echarts/map/js/province/fujian';
                    break;
                case "浙江":
                    jsFile = 'libs/echarts/map/js/province/zhejiang';
                    break;
                case "江苏":
                    jsFile = 'libs/echarts/map/js/province/jiangsu';
                    break;
                case "吉林":
                    jsFile = 'libs/echarts/map/js/province/jilin';
                    break;
                case "辽宁":
                    jsFile = 'libs/echarts/map/js/province/liaoning';
                    break;
                case "台湾":
                    jsFile = 'libs/echarts/map/js/province/taiwan';
                    break;
                case "新疆":
                    jsFile = 'libs/echarts/map/js/province/xinjiang';
                    break;
                case "广西":
                    jsFile = 'libs/echarts/map/js/province/guangxi';
                    break;
                case "宁夏":
                    jsFile = 'libs/echarts/map/js/province/ningxia';
                    break;
                case "内蒙古":
                    jsFile = 'libs/echarts/map/js/province/neimenggu';
                    break;
                case "西藏":
                    jsFile = 'libs/echarts/map/js/province/xicang';
                    break;
                case "香港":
                    jsFile = 'libs/echarts/map/js/province/xianggang';
                    break;
                case "澳门":
                    jsFile = 'libs/echarts/map/js/province/aomen';
                    break;
                case "河北-电":
                    jsFile = 'libs/echarts/map/js/province/heibeidian';
                    break;
                default:
                    break;
            }
            return jsFile;
        }

        var mapDate = [
            {
                value: 'china',
                text: '中国'
            },
            {
                value: 'world',
                text: '世界地图'
            },
            {
                value: '北京',
                text: '北京'
            },
            {
                value: '天津',
                text: '天津'
            },
            {
                value: '上海',
                text: '上海'
            },
            {
                value: '重庆',
                text: '重庆'
            },
            {
                value: '广东',
                text: '广东'
            },
            {
                value: '青海',
                text: '青海'
            },
            {
                value: '四川',
                text: '四川'
            },
            {
                value: '海南',
                text: '海南'
            },
            {
                value: '陕西',
                text: '陕西'
            },
            {
                value: '甘肃',
                text: '甘肃'
            },
            {
                value: '云南',
                text: '云南'
            },
            {
                value: '湖南',
                text: '湖南'
            },
            {
                value: '湖北',
                text: '湖北'
            },
            {
                value: '黑龙江',
                text: '黑龙江'
            },
            {
                value: '贵州',
                text: '贵州'
            },
            {
                value: '山东',
                text: '山东'
            },
            {
                value: '江西',
                text: '江西'
            },
            {
                value: '河南',
                text: '河南'
            },
            {
                value: '河北',
                text: '河北'
            },
            {
                value: '山西',
                text: '山西'
            },
            {
                value: '安徽',
                text: '安徽'
            },
            {
                value: '福建',
                text: '福建'
            },
            {
                value: '浙江',
                text: '浙江'
            },
            {
                value: '江苏',
                text: '江苏'
            },
            {
                value: '吉林',
                text: '吉林'
            },
            {
                value: '辽宁',
                text: '辽宁'
            },
            {
                value: '台湾',
                text: '台湾'
            },
            {
                value: '新疆',
                text: '新疆'
            },
            {
                value: '广西',
                text: '广西'
            },
            {
                value: '宁夏',
                text: '宁夏'
            },
            {
                value: '内蒙古',
                text: '内蒙古'
            },
            {
                value: '西藏',
                text: '西藏'
            },
            {
                value: '香港',
                text: '香港'
            },
            {
                value: '澳门',
                text: '澳门'
            }
        ];
        var property = {
            name: '通用属性',
            config: "property",
            option: []
                .concat($.extend(true, [], Meta.titleProperties))
                .concat($.extend(true, [], Meta.legendProperties))
                .concat($.extend(true, [], Meta.tooltipProperties))
                .concat($.extend(true, [], Meta.toolboxProperties))
                .concat($.extend(true, [], Meta.visualMapProperties))
                .concat([
                    {
                        group: '序列',
                        id: 'f53a0a43-6d1b-43e0-b514-122a8b155ece',
                        name: '序列',
                        type: 'group',
                        items: [],
                        option: [
                            {
                                id: '8d613598-8e08-49ce-908e-7524c305910f',
                                name: '序列名称',
                                enable: true,
                                type: 'text',
                                value: '',
                                link: 'name',
                                tooltip: '序列名称，用于legend'
                            },
                            {
                                id: '17994381-e1fe-4551-a852-a5a0571ed899',
                                name: '序列绑定',
                                enable: true,
                                type: 'seriesBinding',
                                dataset: '',
                                dimension: '',
                                measure: '',
                                tooltip: '序列绑定设置，与数据集关系'
                            },
                            {
                                id: 'a320684c-8ca5-49f0-aab7-853e0fde9e5c',
                                name: '过滤列名称',
                                enable: false,
                                type: 'text',
                                value: '',
                                default: '',
                                tooltip: '绑定数据集，客户端过滤字段列名称'
                            },
                            {
                                id: '96f30ae6-6fe0-4faa-8b7f-a302a49a0434',
                                name: '过滤列默认值',
                                enable: false,
                                type: 'text',
                                value: '',
                                default: '',
                                tooltip: '绑定数据集，客户端过滤字段默认值'
                            },
                            {
                                id: 'f53a0a43-6d1b-43e0-b514-122a8b155ecd',
                                name: '地图选择',
                                type: 'select',
                                enable: false,
                                value: 'china',
                                default: 'china',
                                data: mapDate,
                                link: 'map',
                                tooltip: '选择需要使用的地图'
                            },
                            {
                                id: 'f53a0a43-6d1b-43e0-b514-122a8b155e02',
                                name: '允许缩放',
                                enable: false,
                                type: 'checked',
                                value: true,
                                default: true,
                                link: 'roam',
                                tooltip: '开启鼠标缩放和平移漫游'
                            },
                            {
                                id: 'f53a0a43-6d1b-43e0-b514-122a8b155e07',
                                name: '缩放',
                                enable: false,
                                type: 'number',
                                value: 1,
                                default: 1,
                                link: 'zoom',
                                tooltip: '当前视角的缩放比例。'
                            },
                            {
                                id: 'f53a0a43-6d1b-43e0-b514-122a8b155e08',
                                name: '最小缩放值',
                                enable: false,
                                type: 'number',
                                value: 1,
                                default: 1,
                                link: 'scaleLimit.min',
                                tooltip: '滚轮缩放控制，最小的缩放值。'
                            },
                            {
                                id: 'f53a0a43-6d1b-43e0-b514-122a8b155e09',
                                name: '最大缩放值',
                                enable: false,
                                type: 'number',
                                value: 10,
                                default: 10,
                                link: 'scaleLimit.max',
                                tooltip: '滚轮缩放控制，最大的缩放值。'
                            }
                        ],
                        link: 'series',
                        tooltip: '字段说明:<br/>分组控件，支持动态扩展，内部可增加支持的类型属性'
                    }
                ]),
            //需要针对组件映射属性至组件Options
            MapOption: function (option) {
                Util.linkOption(this.option, option);
            }
        };

        var map = Chart.extend({
            constructor: function (layout) {
                this._layout = layout;
                this._chart = null;
                this._lastdata = null;
                this._container = null;
                this._option = {
                    Binding: [],
                    Events: [],
                    Extend: $.extend(true, {}, property),
                    Option: {
                        title: {
                            text: 'iphone销量',
                            subtext: '纯属虚构',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 'left',
                            data: ['iphone3', 'iphone4', 'iphone5']
                        },
                        visualMap: {
                            min: 0,
                            max: 2500,
                            left: 'left',
                            top: 'bottom',
                            text: ['高', '低'],           // 文本，默认为数值文本
                            calculable: true
                        },
                        series: [
                            {
                                name: 'iphone3',
                                type: 'map',
                                map: mapType,
                                coordinateSystem: 'geo',
                                roam: false,
                                label: {
                                    normal: {
                                        show: true
                                    },
                                    emphasis: {
                                        show: true
                                    }
                                },
                                data: []
                            }
                        ]
                    }
                };
            },
            init: function (element) {
                try {
                    this._container = element;
                } catch (e) {
                    log.error(e);
                }
            },
            _bindEvent: function () {
                var _this = this;
                this._chart.on("click", function (param) {
                    if (_this._layout
                        && _this._layout.navigate
                        && _this._option.Events
                        && _this._option.Events.length > 0) {

                        var registerEvent = _.findWhere(_this._option.Events, {Event: "SeriesClick"});
                        if (registerEvent) {
                            var pageId = registerEvent.PageId;
                            var params = registerEvent.Params;
                            var args = [];
                            var dParam = _.findWhere(params, {Value: "Dimension"});
                            if (dParam && dParam.ParamName) {
                                args.push({
                                    ParamName: dParam.ParamName,
                                    ParamValue: param.name
                                });
                            }
                            var mParam = _.findWhere(params, {Value: "Measure"});
                            if (mParam && mParam.ParamName) {
                                args.push({
                                    ParamName: mParam.ParamName,
                                    ParamValue: param.value
                                });
                            }
                            var sParam = _.findWhere(params, {Value: "SeriesName"});
                            if (sParam && sParam.ParamName) {
                                args.push({
                                    ParamName: sParam.ParamName,
                                    ParamValue: param.seriesName
                                });
                            }
                            _this._layout.navigate(pageId, args);

                        }
                        param.event.event.preventDefault();
                    }
                });
                if (!this._filterDataHandle) {
                    this._filterDataHandle = function (params) {
                        _this.filterDataHandle.call(_this, params);
                    };
                }
                this._layout.removeListener("filterData", this._filterDataHandle);
                this._layout.addListener("filterData", this._filterDataHandle);
            },
            filterDataHandle: function (params) {
                var _this = this;
                var flag = false;
                var seriesItems = _.findWhere(_this._option.Extend.option, {type: 'group'});
                $.each(seriesItems.items, function (i, item) {
                    var filterColumn = _.findWhere(item.option, {name: '过滤列名称'});
                    var filterValue = _.findWhere(item.option, {name: '过滤列默认值'});

                    if (filterColumn && filterValue
                        && filterColumn.enable && filterValue.enable
                        && filterColumn.value !== "" && filterValue.value !== ""
                    ) {
                        for (var prop in params) {
                            if (!params.hasOwnProperty(prop)) continue;
                            if (filterColumn.value === prop) {
                                filterValue.value = params[prop];
                                flag = true;
                            }
                        }
                    }
                });
                if (flag && _this._lastdata) {
                    _this.setData(_this._lastdata);
                }
            },
            example: function () {
                try {
                    this._option.Option.series[0].data = [
                        {name: '北京', value: randomData()},
                        {name: '天津', value: randomData()},
                        {name: '上海', value: randomData()},
                        {name: '重庆', value: randomData()},
                        {name: '河北', value: randomData()},
                        {name: '河南', value: randomData()},
                        {name: '云南', value: randomData()},
                        {name: '辽宁', value: randomData()},
                        {name: '黑龙江', value: randomData()},
                        {name: '湖南', value: randomData()},
                        {name: '安徽', value: randomData()},
                        {name: '山东', value: randomData()},
                        {name: '新疆', value: randomData()},
                        {name: '江苏', value: randomData()},
                        {name: '浙江', value: randomData()},
                        {name: '江西', value: randomData()},
                        {name: '湖北', value: randomData()},
                        {name: '广西', value: randomData()},
                        {name: '甘肃', value: randomData()},
                        {name: '山西', value: randomData()},
                        {name: '内蒙古', value: randomData()},
                        {name: '陕西', value: randomData()},
                        {name: '吉林', value: randomData()},
                        {name: '福建', value: randomData()},
                        {name: '贵州', value: randomData()},
                        {name: '广东', value: randomData()},
                        {name: '青海', value: randomData()},
                        {name: '西藏', value: randomData()},
                        {name: '四川', value: randomData()},
                        {name: '宁夏', value: randomData()},
                        {name: '海南', value: randomData()},
                        {name: '台湾', value: randomData()},
                        {name: '香港', value: randomData()},
                        {name: '澳门', value: randomData()}
                    ];
                    var _this = this;
                    setTimeout(function () {
                        _this.setData({});
                    }, 1000);
                } catch (e) {
                    log.error(e);
                }
            },
            _readProperty: function () {
                try {
                    if (!this._option.Extend) return;
                    Util.deepMapOption(property, this._option.Extend, this._option.Option);
                } catch (e) {
                    log.error(e);
                }
            },
            //TODO:需要重写的部分
            _bindData: function (data) {
                var tables = data;
                var _this = this;

                //根据每个option自行查找，可通过id或name，这里因为只有一个group,因此通过type查找
                var seriesItems = _.findWhere(this._option.Extend.option, {type: 'group'});

                //清除工作
                if (seriesItems.items.length > 0) {
                    this._option.Option.legend.data = [];

                }

                //绑定数据
                $.each(seriesItems.items, function (i, item) {
                    var bindProperty = _.findWhere(item.option, {type: 'seriesBinding'});
                    if (!bindProperty) return;

                    var dataSetCode = bindProperty.dataset;
                    var dimensionCode = bindProperty.dimension.ColumnCode;
                    var measureCode = bindProperty.measure.ColumnCode;

                    var nameProperty = _.findWhere(item.option, {name: '序列名称'});
                    if (nameProperty) {
                        _this._option.Option.legend.data.push(nameProperty.value);
                    }

                    if (dataSetCode && dimensionCode && measureCode) {
                        var table = tables[dataSetCode];

                        var binding = _.findWhere(_this._option.Binding, {DataSetCode: dataSetCode});
                        var dimension = _.findWhere(binding.Dimensions, {Code: dimensionCode}).Column;
                        var measure = _.findWhere(binding.Measures, {Code: measureCode}).Column;
                        var data = [];

                        table = _this._filterTable(item.option, table);
                        $.each(table, function (j, row) {
                            data.push({
                                name: row[dimension],
                                value: row[measure]
                            });
                        });
                        if (_this._option.Option.series.length >= i + 1) {
                            _this._option.Option.series[i].data = data;
                        }
                    }
                });
            },
            _filterTable: function (option, table) {
                var filterColumn = _.findWhere(option, {name: '过滤列名称'});
                var filterValue = _.findWhere(option, {name: '过滤列默认值'});

                if (filterColumn && filterValue
                    && filterColumn.enable && filterValue.enable
                    && filterColumn.value !== "" && filterValue.value !== ""
                ) {
                    var tableCopy = _.map(table, _.clone);
                    return _.filter(tableCopy, function (row) {
                        return row[filterColumn.value] === filterValue.value;
                    });
                }
                return table;
            },
            setData: function (data) {
                try {
                    this._lastdata = data;

                    var _this = this;
                    this._readProperty();
                    var mapList = _.map(this._option.Option.series, function (s) {
                        if (s.map) {
                            return FindMapJsFile(s.map);
                        }
                    });
                    if (_this._option.Option.geo && _this._option.Option.geo.map) {
                        mapList.push(FindMapJsFile(_this._option.Option.geo.map));
                    }
                    mapList = _.filter(mapList, function (m) {
                        return m !== undefined;
                    });
                    if (_this._chart) {
                        _this.dispose();
                    }
                    require(mapList, function () {
                        _this._chart = ec.init(_this._container, null, {
                            renderer: 'canvas'
                        });
                        _this._bindEvent();
                        if (data
                            && _this._option.Binding
                            && _this._option.Binding.length > 0
                            && _this._option.Extend) {

                            _this._bindData(data);
                            _this._readProperty();
                        }
                        _this._chart.setOption(_this._option.Option, true);
                    });
                } catch (e) {
                    log.error(e);
                }
            },
            setOption: function (option) {
                try {
                    return this._option = $.extend(true, {}, option);
                } catch (e) {
                    log.error(e);
                }
            },
            getOption: function () {
                try {
                    this._readProperty();
                } catch (e) {
                    log.error(e);
                }
                return this._option;
            },
            setTheme: function (theme) {
                try {
                    this._chart.setTheme(theme);
                } catch (e) {
                    log.error(e);
                }
            },
            resize: function () {
                try {
                    this._chart.resize();
                } catch (e) {
                    log.error(e);
                }
            },
            showLoading: function () {
                try {
                    if (this._layout && this._layout.showLoading) {
                        this._layout.showLoading(this);
                    }
                } catch (e) {
                    log.error(e);
                }
            },
            hideLoading: function () {
                try {
                    if (this._layout && this._layout.hideLoading) {
                        this._layout.hideLoading(this);
                    }
                } catch (e) {
                    log.error(e);
                }
            },
            dispose: function () {
                try {
                    this._chart.dispose();
                    //$(this._container).empty();
                    this._layout.removeListener("filterData", this._filterDataHandle);
                } catch (e) {
                    log.error(e);
                }
            },
            getElement: function () {
                return this._container;
            },
            getChart: function () {
                return this._chart;
            }
        });

        return {
            Chart: map,
            Property: property
        };
    });
